/* eslint-disable react/display-name */
import React from 'react'
import { View, Text, Image, AppState, DeviceEventEmitter } from 'react-native'
import PropTypes from 'prop-types'
import { createBottomTabNavigator, createAppContainer } from 'react-navigation'
import JPushModule from 'jpush-react-native'
import RNIap, {
  purchaseErrorListener,
  purchaseUpdatedListener
} from 'react-native-iap'
import { IS_IOS } from 'src/utils/ScreenUtil'
import BHomePage from './home/home-page/index2'
import BMessagePage from './message/message-page'
import BMinePage from './main/main-page/index'
// import BMinePage from './main/main-page/index2'
/* redux */
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_USERINFO_B_ACTION
} from 'src/store/actions/userinfo'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from './main/main-page/store/action'
import IMController from 'src/utils/IMController'
import TouchableBounce from 'react-native/Libraries/Components/Touchable/TouchableBounce'
import { isString } from 'src/utils/JSTypeUtil'
import BackHandlerUtil from 'src/utils/BackHandlerUtil'
import { initKeywordBlockObj } from 'src/utils/RegUtil'

export const Bridge = function () {
  return <View
    style={{ position: 'absolute', backgroundColor: 'red', top: -2, right: -6, width: 8, height: 8, borderRadius: 4 }} />
}
export const tabBarIconStyle = { width: 21, height: 21 }
export const B_HOME_REFRESH = 'B_HOME_REFRESH' // B端首页刷新监听KEY

const TabRouteConfigs = {
  BHomePage: {
    screen: BHomePage,
    navigationOptions: ({ screenProps: { activeIndex } }) => {
      const refreshClick = activeIndex === 0

      return {
        tabBarLabel: '首页',
        tabBarIcon: ({ focused }) => (
          <Image
            style={tabBarIconStyle}
            source={focused ? require('../imgC/tab/home_selected.png') : require('../imgC/tab/home.png')} />),
        tabBarOnPress: ({ defaultHandler }) => {
          if (refreshClick) {
            // 需要刷新
            DeviceEventEmitter.emit(B_HOME_REFRESH)
          }
          defaultHandler()
        },
        tabBarButtonComponent: refreshClick ? TouchableBounce : null
      }
    }
  },
  BMessagePage: {
    screen: BMessagePage,
    navigationOptions: ({ screenProps }) => ({
      tabBarLabel: '消息',
      tabBarIcon: ({ focused }) => {
        return (
          <View style={{ position: 'relative' }}>
            {!!screenProps.bridge && <Bridge />}
            <Image
              style={tabBarIconStyle}
              source={focused ? require('../imgC/tab/message_selected.png') : require('../imgC/tab/message.png')} />
          </View>)
      }
    })
  },
  BMinePage: {
    screen: BMinePage,
    navigationOptions: {
      tabBarLabel: '我的',
      tabBarIcon: ({ focused }) => (
        <Image
          style={tabBarIconStyle}
          source={focused ? require('../imgC/tab/mine_selected.png') : require('../imgC/tab/mine.png')} />)
    }
  }
}

const BottomTabNavigatorConfig = {
  initialRouteName: 'BHomePage',
  tabBarOptions: {
    activeTintColor: '#3C3C3C',
    inactiveTintColor: '#999999',
    labelStyle: {
      fontSize: 10,
      fontWeight: '400'
    },
    tabStyle: {
      paddingVertical: 5
    },
    style: {
      backgroundColor: '#F7F7F7',
      borderTopWidth: 0
    }
  },
  lazy: true,
  // backBehavior: 'none',
  keyboardHidesTabBar: true
}
const TabNavigator = createBottomTabNavigator(
  TabRouteConfigs,
  BottomTabNavigatorConfig
)
const TabbarContainer = createAppContainer(TabNavigator)

const mapActiontoProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  doRequestUserInfoB (...payload) {
    const promise = DO_REQUEST_USERINFO_B_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPage (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})
const mapStatetoProps = ({ userinfo, BMineCenterStore, im }) => (
  {
    userinfo,
    BMineCenterStore,
    isRed: im.isRed
  }
)

class MainTab extends React.Component {
  static router = TabbarContainer.router

  render () {
    const { screenProps, navigation, isRed } = this.props
    const bridge = !!isRed
    const { state: { index: activeIndex } } = navigation
    return <TabbarContainer screenProps={{ ...screenProps, bridge, activeIndex }} navigation={navigation} />
  }

  componentDidMount () {
    console.log('BMainTab componentDidMount', this.props)
    const {
      userinfo: { userId }, doRequestUserInfoB, doRequestMainPage
    } = this.props
    if (userId) {
      doRequestUserInfoB({ params: { userId } }).then(() => {
        return doRequestMainPage({ userId })
      })
    }
    this.jpushConfigInit()
    // IS_IOS && this.purchaseInitIOS()
    AppState.addEventListener('change', this.handleAppStateChange)
    initKeywordBlockObj()
  }

  componentDidUpdate (prevProps) {
    this.jpushConfigUpdate(prevProps.userinfo.userId, this.props.userinfo.userId)
    this.imConfigUpdate(prevProps.BMineCenterStore.haveCompanyApply.companyDone, this.props.BMineCenterStore.haveCompanyApply.companyDone)
  }

  jpushConfigInit = () => {
    // JPushModule.initPush()
    if (IS_IOS) {
      JPushModule.getRegistrationID(this.getRegistrationIDHandle)
      JPushModule.getLaunchAppNotification(this.getLaunchAppNotificationHandle)
      JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)
      JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener)
    } else {
      JPushModule.initPush()
      JPushModule.getInfo(map => {
        console.info('notifyJSDidLoad', map)
      })
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
          console.info('notifyJSDidLoad')
          JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)
          JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener)
          JPushModule.addGetRegistrationIdListener(this.getRegistrationIdListener)
        }
      })
    }
  }

  jpushConfigDeinit = () => {
    JPushModule.removeReceiveNotificationListener(this.receiveNotificationListener)
    JPushModule.removeReceiveOpenNotificationListener(this.openNotificationListener)
    console.log('Will clear all notifications')
    JPushModule.clearAllNotifications()
  }

  jpushConfigUpdate = (prevUserId, userId) => {
    if (!prevUserId && userId) {
      console.log('BMainTab 重新登录')
      JPushModule.setAlias(`b_${userId}`, result => {
        console.log('setAlias', result)
      })
    } else if (prevUserId && !userId) {
      console.log('BMainTab 退出登录')
      JPushModule.deleteAlias(() => {
        console.log('deleteAlias')
      })
    }
  }

  imConfigUpdate = (prevCompanyDone, companyDone) => {
    if (!prevCompanyDone && companyDone) {
      console.log('im 重新登录')
      IMController.initNIMb()
    } else if (prevCompanyDone && !companyDone) {
      console.log('im 退出登录')
      IMController.destroy().then(() => {
        IMController.initData()
      })
    }
  }

  /* jupush */
  getRegistrationIDHandle = registrationId => {
    console.log('getRegistrationIDHandle, registrationId ' + registrationId)
    const { userinfo: { userId } } = this.props
    JPushModule.deleteAlias(() => {
      console.log('deleteAlias')
      if (registrationId && userId) {
        JPushModule.setAlias(`b_${userId}`, result => {
          console.log('setAlias', result)
        })
      }
    })
  }

  /* iOS Only 点击推送启动应用的时候原生会将该 notification 缓存起来，该方法用于获取缓存 notification */
  getLaunchAppNotificationHandle = map => {
    console.log('getLaunchAppNotificationHandle map: ' + map && JSON.stringify(map))
    this.openNotificationListener(map)
  }

  /* 监听：接收推送事件 */
  receiveNotificationListener = map => {
    console.log('receiveNotificationListener map: ' + map && JSON.stringify(map))
  }

  /* 监听：点击推送事件 */
  openNotificationListener = (map = {}) => {
    console.info('openNotificationListener map: ' + map && JSON.stringify(map))
    const { extras = {} } = map
    const extrasObj = isString(extras) ? JSON.parse(extras) : extras
    const { pushType } = extrasObj
    console.info('openNotificationListener pushType', pushType)
    switch (pushType) {
      case 'im':
        this.props.navigation.navigate('BMessagePage')
        break
      default:
        break
    }
  }

  /* Android Only  If device register succeed, the server will return registrationId */
  getRegistrationIdListener = registrationId => {
    console.log('Device register succeed, registrationId ' + registrationId)
  }

  purchaseInitIOS = () => {
    RNIap.getProducts(['vip001', 'vip002', 'vip003']).then(res => {
      console.log('getProducts', res)
      // return RNIap.requestPurchase('vip001', false)
    }).then(res => {
      console.log('requestPurchase vip001', res)
    })
    RNIap.getAvailablePurchases().then(res => {
      console.log('getAvailablePurchases', res)
    })

    this.purchaseUpdateSubscription = purchaseUpdatedListener((purchase) => {
      console.log('purchaseUpdatedListener', purchase)
      const receipt = purchase.transactionReceipt
      if (receipt) {
      }
    })
    this.purchaseErrorSubscription = purchaseErrorListener((error) => {
      console.warn('purchaseErrorListener', error)
    })
  }

  purchaseDeinitIOS = () => {
    if (this.purchaseUpdateSubscription) {
      this.purchaseUpdateSubscription.remove()
      this.purchaseUpdateSubscription = null
    }
    if (this.purchaseErrorSubscription) {
      this.purchaseErrorSubscription.remove()
      this.purchaseErrorSubscription = null
    }
  }

  handleAppStateChange = appState => {
    console.log('handleAppStateChange')
    if (appState === 'inactive') {
      JPushModule.clearAllNotifications()
    }
  }

  componentWillUnmount () {
    console.log('BMainTab componentWillUnmount')
    this.jpushConfigDeinit()
    AppState.removeEventListener('change', this.handleAppStateChange)
  }
}

MainTab.propTypes = {
  userinfo: PropTypes.object,
  BMineCenterStore: PropTypes.object,
  navigation: PropTypes.object,
  isRed: PropTypes.bool
}
export default connect(
  mapStatetoProps,
  mapActiontoProps
)(MainTab)
